$(function(){
	var _id = parseInt($_GET['id']);
	/**
	 * @desc 商品信息
	 */
	var global_pay = {
			'page': $_GET['page'] ? $_GET['page'] : undefined,//页码
			'pageSize' : $_GET['pageSize'] ? $_GET['pageSize'] : undefined, //页数
			'vendor': undefined,//往来单位
			'starTime': undefined,//开始时间
			'endTime' : undefined,//截至时间
			'name' : undefined,
	}
	var global_count = 1;
	var global_remove = [];
	var select_units;
	//时间
	dateSelFun($('#settle_time'));
	
	

	
	if(_id){
		initSettles();
	}
	/**
	 * @初始化页面
	 */
	function initSettles() {
		$('#confirm').show();
		$('#save').attr('data-id',parseInt(_id));
		$.get('get-settle-payables-info', {'id' : _id}, function(data, status) {
			if(status =='success' && data.Ack =='Success'){
				var H = data.Body.head;
				if(H){
					$('#settle_no').val(H.settle_pay_no);
					$('#settle_type').val(H.settle_pay_type);
					$('#settle_time').val(intToLocalDate(H.settle_pay_date,1));
					$('#handle_man').val(H.settle_man);
					$('#vendor').val(H.vendor_id);
					$('#remark').val(H.remark);
					$('#settle_amount').val(H.settle_amount);
					$('#discount_amount').val(H.discount_amount);
					$('#create_man').val(H.username).attr('data-id', H.create_man);
					if(+H.confirm_flag){
						$('#save').attr('style','display:none');
						$('#confirm').removeClass().addClass('btn btn-warning btn-sm pull-right').attr('disabled','disabled');
					}
				}
				var D = data.Body.det.list;
				if(D){
					$('#stockList').find('tr').remove();
					for(var i in D){
						$('<tr>'
						   +'<td class="text-center" name="ids" data-id="'+D[i].settle_pay_det_id+'" data-payid="'+D[i].pay_id+'">'+(+i+1)+'</td>'
						   +'<td class="text-center"><a href="javascript:void(0)"class="stock-minus-tr" data-id=""> <i class="fa fa-minus-circle" style="color:red;" ></i></a></td>'
						   +'<td class="text-center" name="name" data-id="'+D[i].settle_pay_id+'"><input title="应付单号" readonly type="text" value="'+D[i].origin_no+'"'
						   +'class="product_name stock-input50"  style="height: 30px;width:80%"> <a class="search-btn search-product" title="搜索"'
						   +'href="javascript:void(0)"><i class="fa fa-search"></i></a></td>'
						   
						   +'<td class="text-center" name="settle_pay_time"><input title="应付款发生日期" type="text" value="'+intToLocalDate(D[i].pay_time,1)+'"></td>'
						   +'<td class="text-center" name="settle_pay_type"><input title="应付款类型" type="text" value="'+D[i].pay_type_name+'"></td>'
						   +'<td class="text-center" name="handle_man"><input title="经手人" type="text" data-id="'+D[i].pay_man+'" value="'+D[i].pay_man_name+'"></td>'
						   +'<td class="text-center" name="settle_pay_amount"><input title="应付金额" type="text" value="'+D[i].pay_amount+'" class="settle_pay_amount" readonly></td>'
						   +'<td class="text-center" name="settle_receive_amount"><input title="已结销金额" type="text" value="'+D[i].settled_amount+'" class="settle_receive_amount" readonly></td>'
						   +'<td class="text-center" name="settle_left_amount"><input title="当前剩余金额" type="text" value="'+D[i].left_amount+'" class="settle_left_amount" readonly></td>'
						   +'<td class="text-center" name="settle_cur_amount"><input title="本次付款金额" type="text" value="'+D[i].current_amount+'" class="settle_cur_amount"></td>'
						   +'<td class="text-center" name="settle_remark"><input title="备注" type="text" value="'+D[i].remark+'"></td>'
						   +'</tr>').appendTo('#stockList');
						global_count++;
					}
					var T = data.Body.det;
					$('#total_payamount').val(T.total_pay_amount);
					$('#total_receiveamount').val(T.total_received_amount);
					$('#total_leftamount').val(T.total_left_amount);
					$('#total_curamount').val(T.total_cur_amount);
				}
			}
		});
	};
	
	
	/**
	 * @desc 选择应付单
	 */
	$('#stockList').on('click','.search-product',function(){
		dateSelFun($('#starTime'));
		dateSelFun($('#endTime'));
		$('#starTime').val('');
		$('#endTime').val('');
		$('#origin_id').val('');
		global_pay.starTime = undefined;
		global_pay.endTime = undefined;
		global_pay.name = undefined;
//		$('#checkAll').prop('checked',false);
		global_pay.page = 1;
		
		getOriginMent();
		
	})
	//过滤
	$('#searchPay').on('click', function() {
		var _name = trim($('#origin_id').val());
		global_pay.name = _name;
		var starTime = $('#starTime').val();
		var endTime = $('#endTime').val();
		if(starTime > endTime){
			alertTips('warning','开始时间不能大于截至时间！');
			return false;
		}
		global_pay.starTime = starTime;
		global_pay.endTime = endTime;
		getOriginMent();
		return;
	})
	
	/**
	 * @desc 获取应付帐单
	 * @date 2017-03-03
	 */
	function getOriginMent(pageInfo)
	{
		if(pageInfo !== undefined){
			global_pay.page = pageInfo.page;
			global_pay.pageSize = pageInfo.pageSize;
		}
		global_pay.vendor = $('#vendor').val();
		if(global_pay.vendor == 0){
			alertTips('error','请先选择往来单位');
			return false;
		}
		$('#origin_header').find('tr').remove();
		var first_id = 0;
		var ii = layer.load();
		$.ajax({
            url: 'get-payables-by-vendor',
            type: "GET",
            cache: true,
            data: global_pay,
            dataType: "json",
            jsonp: "callback",
            global:false,
            success: function(data){
           	 layer.close(ii);
           	 var P = data.Body.list;
					if(P && P.length){
						for(var i in P){
							$('<tr>'
							+'<td class="text-center"><input type="checkbox" class="ids"  data-id="'+P[i].pay_id+'" checked></td>'
							+'<td class="text-center">'+(+i+1)+'</td>'
							+'<td class="text-center date">'+intToLocalDate(P[i].pay_time,1)+'</td>'
							+'<td class="text-center no" data-id="'+P[i].pay_id+'">'+P[i].origin_no+'</td>'
							+'<td class="text-center pay_type" data-id="'+P[i].pay_type+'">'+P[i].pay_type_name+'</td>'
							+'<td class="text-center pay_man" data-id="'+P[i].pay_man+'">'+P[i].employee_name+'</td>'
							+'<td class="text-center pay_amount">'+P[i].pay_amount+'</td>'
							+'<td class="text-center receive_amount">'+P[i].receive_amount+'</td>'
							+'<td class="text-center left_amount">'+P[i].left_amount+'</td>'
							+'<td class="text-center description">'+P[i].description+'</td>'
							+'<td class="text-center remark">'+P[i].remark+'</td>'
							+'</tr>').appendTo('#origin');
						}
						first_id = P[0].procurement_id;//记录第一个id
						var pageInfo = data.Body.page;
			            if (typeof pageInfo !== 'undefined'){
			              	refreshPaginationNavBar2($('.paginationNavBar'), pageInfo.page, pageInfo.pageSize, data.Body.count, getOriginMent);
			            }
			            
					}else {
						$('<tr><td colspan="11" class="text-center">没有数据</td></tr>').appendTo('#origin_header');
						refreshPaginationNavBar2($('.paginationNavBar'), 1, 10, 1, getOriginMent);
					}
					$('#chooseOrigin').modal('show');//选择订单窗口
					
            }
		})
		
	}
	
	/**
	 * @desc 全选应付单
	 */
	$('#checkAll').on('click', function(){
		if($(this).prop('checked')){
			$('.ids').prop('checked', true);
		} else {
			$('.ids').prop('checked',false);
		}
	})
	
	/**
	 * @desc 选择应付账单明细
	 */
	$('#choosiePay').on('click',function(){
		//判断应付单是否已被未确认的应付结算单占用
		var tmp_flag = 0;
		$('#origin_header').find('tr').each(function(iindex,cell){
			var pay_id = $(cell).find('.no').attr('data-id');
			var no = $(cell).find('.no').text();
			var flag = $(cell).find('.ids').prop('checked');
			if(flag){
//				$.get('check-payables-by-id',{'id':pay_id}, function(data,status){
//					if(status =='success' && data.Ack =='Success'){
////						alertTips('error','已有应付结算单调用了:'+no+'，请先去确认入库单');
//						tmp_flag = 1;
//						console.log(tmp_flag);
//						return false;
//					} else {
//						InsertPayables()
//					}
//				})
				
				$.ajax({
				      type: "get",
				      url: 'check-payables-by-id',
				      data: {'id':pay_id},
				      dataType:'json',
				      async: false,
				      success: function(data) { 
				    	  if(data.Ack =='Success'){
				    		  tmp_flag = 1;
				    		  return false;
				    	  }
				      },
				});
				if(tmp_flag){
					alertTips('error','已有应付结算单调用了:'+no+'，请先去确认入库单');
					return false;
				}
			}
		});
		
		if(!tmp_flag){
			InsertPayables();
		}
		
	});
	
	function InsertPayables()
	{
		if(global_count == 1){
			$('#stockList').find('tr').remove();
		}
		var choose_flag = 0;
		$('#origin_header').find('tr').each(function(index,element){
			var flag = $(element).find('.ids').prop('checked');
			if(flag){
				choose_flag = 1;
				var pay_time = $(element).find('.date').text();
				var pay_id = $(element).find('.no').attr('data-id');
				var check_flag = 0;
				$('#stockList').find('[name="ids"]').each(function(ii,ele){
					if(pay_id == $(ele).attr('data-payid')){
						check_flag = 1;
					}
				})
				if(check_flag){
					return;
				}
				var no =  $(element).find('.no').text();
				var pay_type_id = $(element).find('.pay_type').attr('data-id');
				var pay_type = $(element).find('.pay_type').text();
				var pay_amount = +$(element).find('.pay_amount').text();
				var receive_amount = +$(element).find('.receive_amount').text();
				var left_amount = +$(element).find('.left_amount').text();
				var description = +$(element).find('.description').text();
				var remark = $(element).find('.remark').text();
				var pay_man = $(element).find('.pay_man').attr('data-id');
				var pay_man_name = $(element).find('.pay_man').text();
				var total_payamount = +$('#total_payamount').val();
				$('#total_payamount').val(total_payamount + pay_amount);
				var total_receiveamount = +$('#total_receiveamount').val();
				$('#total_receiveamount').val(total_receiveamount + receive_amount);
				var total_leftamount = +$('#total_leftamount').val();
				$('#total_leftamount').val(total_leftamount + left_amount);
				
				$('<tr>'
				   +'<td class="text-center" name="ids" data-payid="'+pay_id+'" data-id="">'+global_count+'</td>'
				   +'<td class="text-center"><a href="javascript:void(0)" class="stock-minus-tr"> <i class="fa fa-minus-circle" style="color:red;"></i>'
				   +'</a></td>'
				   +'<td class="text-center">'
				   +'<input title="应付单号" type="text" value="'+no+'" data-id="'+pay_id+'"'
				   +'class="origin_no stock-input50" readonly '
				   +'style="height: 30px;width:80%"> <a class="search-btn search-product" title="搜索"'
				   +'href="javascript:void(0)"><i class="fa fa-search"></i></a></td>'
				   +'<td class="text-center" name="settle_pay_time"><input title="应付款发生日期" type="text" value="'+pay_time+'"></td>'
				   +'<td class="text-center" name="settle_pay_type"><input title="应付款类型" type="text" value="'+pay_type+'"></td>'
				   +'<td class="text-center" name="handle_man"><input title="经手人" type="text" data-id="'+pay_man+'" value="'+pay_man_name+'"></td>'
				   +'<td class="text-center" name="settle_pay_amount"><input title="应付金额" type="text" value="'+pay_amount+'" class="settle_pay_amount" readonly></td>'
				   +'<td class="text-center" name="settle_receive_amount"><input title="已结销金额" type="text" value="'+receive_amount+'" class="settle_receive_amount" readonly></td>'
				   +'<td class="text-center" name="settle_left_amount"><input title="当前剩余金额" type="text" value="'+left_amount+'" class="settle_left_amount" readonly></td>'
				   +'<td class="text-center" name="settle_cur_amount"><input title="本次付款金额" type="text" value="0.00" class="settle_cur_amount"></td>'
				   +'<td class="text-center" name="settle_remark"><input title="备注" type="text" value=""></td>'
				   +'').appendTo('#stockList')
				   global_count++;
			}
			
		})
		if(!choose_flag){
			alertTips('warning','请勾选付款明细！');
			return false;
		}
	}
	
	//删除数据
	$('#stockList').on('click','.stock-minus-tr',function(){
		var tmp_id = $(this).closest('td').prev('td').attr('data-id');
		if ($.inArray(tmp_id, global_remove) >= 0) {
			return false;
		}
		if(tmp_id){
			global_remove.push({'settle_pay_det_id':tmp_id});
		}
		
		
		if(global_count == 1){
			return false;
		} else if(global_count == 2){
			//添加一条数据要删除数据 后插入一条空数据
			$('#stockList').find('tr:first').remove();
			global_count--;
			insertOrginHtml();
			SumAmount();
			return false;
		} else {
			var self = $(this);
			//判断当前要删除的行,下面是否还有记录
            var nextTr = self.parent().parent().next('tr');
            if(nextTr.length){
            	//存在下一行，清空当前行数据
                self.closest('tr').remove();
                // 序号重新排列
                var td = $('#stockList').find('tr').find('td:first');
                $.each(td, function(index, item) {
                    var item = $(item);
                    item.text(index+1);
                })
                global_count--;
                SumAmount();
                return false;
            } else{
            	//删除的为最后一行
                self.closest('tr').remove();
                global_count--;
                SumAmount();
                return false;
            }
		}
		
	});
	
	var insertOrginHtml = function(){
		$('<tr>'
				  +'<td class="text-center" name="ids" data-id="" data-payid="">'+global_count+'</td>'
				  +'<td class="text-center"><a href="javascript:void(0)"class="stock-minus-tr" data-id=""> <i class="fa fa-minus-circle" style="color:red;" ></i></a></td>'
				  +'<td class="text-center" name="name" data-id=""><input title="商品名称" readonly type="text" value=""'
				  +'class="product_name stock-input50"  style="height: 30px;width:80%"> <a class="search-btn search-product" title="搜索"'
				  +'href="javascript:void(0)"><i class="fa fa-search"></i></a></td>'
				  +'<td class="text-center" name="settle_pay_time"><input title="应付款发生日期" type="text"	class="num stock-input"></td>'
				  +'<td class="text-center" name="settle_pay_type"><input title="应付款类型" type="text" class="num stock-input"></td>'
				  +'<td class="text-center" name="handle_man"><input title="经手人" type="text" value="0.00"></td>'
				  +'<td class="text-center" name="settle_pay_amount"><input title="应付金额" type="text" value="0.00" class="settle_pay_amount"></td>'
				  +'<td class="text-center" name="settle_receive_amount"><input title="已结销金额" type="text" value="0.00" class="settle_receive_amount"></td>'
				  +'<td class="text-center" name="settle_left_amount"><input title="当前剩余金额" type="text" value="0.00" class="settle_left_amount"></td>'
				  +'<td class="text-center" name="settle_cur_amount"><input title="本次付款金额" type="text" value="0.00" class="settle_cur_amount"></td>'
				  +'<td class="text-center" name="settle_remark"><input title="备注" type="text" 	class="remark stock-input" style="width: 100%;"></td>'
				  +'</tr>').appendTo('#stockList');
	};
	
	$('#stockList').on('blur','.settle_cur_amount',function(){
		this.value = parseFloat($(this).val());
//		if(isNaN(parseFloat($(this).val()))){
//			alertTips('warning','本次付款金额填写错误，请重新填写！');
//			return false;
//		} // 保存时验证
		var cur_amount = $(this).val();
		var left_amount = +$(this).closest('td').prev('td').find('input').val();
		if(cur_amount > left_amount){
			alertTips('warning','本次付款金额大于剩余金额，请重新输入！');
			return false;
		}
		SumAmount();
	});

	/**
	 * @var 计算总金额
	 */
	var SumAmount = function(){
		var total_curamount = 0;
		$('#stockList tr').find('.settle_cur_amount').each(function(index,element){
			var _amount = $(element).val();
			if(_amount ==''){
				
			} else {
				total_curamount += +_amount;
			}
			
		})
		$('#total_curamount').val(total_curamount);
		var total_payamount = 0;
		$('#stockList tr').find('.settle_pay_amount').each(function(index,element){
			var _amount = $(element).val();
			if(_amount ==''){
				
			} else {
				total_payamount += +_amount;
			}
			
		})
		$('#total_payamount').val(total_payamount);
		
		var total_recamount = 0;
		$('#stockList tr').find('.settle_receive_amount').each(function(index,element){
			var _amount = $(element).val();
			if(_amount ==''){
				
			} else {
				total_recamount += +_amount;
			}
			
		})
		$('#total_receiveamount').val(total_recamount);
		
		var total_leftamount = 0;
		$('#stockList tr').find('.settle_left_amount').each(function(index,element){
			var _amount = $(element).val();
			if(_amount ==''){
				
			} else {
				total_leftamount += +_amount;
			}
			
		})
		$('#total_leftamount').val(total_leftamount);
	};
	
	
	
	(function() {
		// 保存
		$('#save').on('click', function() {
			//单头
			var head = pay_header();
			if(!head){
				return false;
			}
			//明细
			var detail = pay_detail();
			if(!detail){
				return false;
			}
			var ii = layer.load();
			$.post('save-settle-payables',{'head':head,'det':detail,'remove': global_remove,'id':_id}, function(data,status){
				setTimeout(function(){
					  layer.close(ii);
				}, 1000);
				if(status =='success'){
					if(data.Ack =='Success'){
						alertTips('success','保存成功');
						setTimeout(function() {
 							window.location.reload();
						}, 1000);
					}
				} else {
					alertShows('error','网络错误');
				}
			})
		});

	})();	

	var pay_header = function() {
		var no = $('#settle_no').val();
		var origin_type = $('#settle_type').val();
		var settle_time = $('#settle_time').val();
		if (settle_time.length == 0) {
			alertTips('warning', '请输入出库时间');
			return false;
		}
		var vendor = $('#vendor').val();
		if (!+vendor) {
			alertTips('warning', '请选择往来单位');
			return false;
		}
		var handle_man = $('#handle_man').val();
		if (!+handle_man) {
			alertTips('warning', '请选择经手人员');
			return false;
		}
//		var settle_amount = $('#settle_amount').val();
//		if(!+settle_amount){
//			alertTips('warning', '请选择付款金额');
//			return false;
//		}
		var remark = $('#remark').val();
		var create_man = $('#create_man').attr('data-id');
		var settle_head = {
			'settle_pay_no' : no,
			'settle_pay_type' : origin_type,
			'settle_pay_date' : settle_time,
			'settle_man' : handle_man,
			'create_man' : create_man,
			'vendor_id' : vendor,
			'remark' : remark,
			'settle_amount':$('#settle_amount').val(),
			'discount_amount':$('#discount_amount').val(),
		};
		return settle_head;
	}
	
	//结算单明细
	var pay_detail = function(){
		var settle_det=[];
		var settle_info = [];
		var _tr = $('#stockList').find('tr');
		var flag = 1;
		if(_tr.length == 1){
			var pid = _tr.first('tr').find('td[name="ids"]').attr('data-payid');
			if(pid == ''){
				alertTips('warning','请选择应付账单');
				return false;
			}
		}
		_tr.each(function(index,element){
			var tr = $(this);
			var settle_cur_amount = tr.find('[name="settle_cur_amount"] input').val();
			if(isNaN(parseFloat(settle_cur_amount))){
				alertTips('warning','本次付款金额填写错误，请重新填写！');
				return false;
			} // 保存时验证
			if(settle_cur_amount == 0){
				alertTips('warning','请填写本次付款金额');
				flag = 0;
				return false;
			}
			var settle_left_amount = +tr.find('[name="settle_left_amount"] input').val();
			if(settle_cur_amount > settle_left_amount){
				alertTips('warning','本次付款金额大于剩余金额，请重新输入！');
				flag = 0;
				return false;
			}
			SumAmount();
			var line_id = tr.find('[name="ids"]').attr('data-id');
			if(line_id == ''){
				line_id = 0;
			}
			
			settle_det = {
				'settle_pay_det_id':line_id,
				'pay_id':tr.find('.origin_no').attr('data-id'),
				'pay_amount':tr.find('[name="settle_pay_amount"] input').val(),
				'settled_amount': tr.find('[name="settle_receive_amount"] input').val(),
				'left_amount': settle_left_amount,
				'current_amount' : settle_cur_amount,
				'remark' : tr.find('[name="settle_remark"] input').val(),
			};
			settle_info.push(settle_det);
			settle_det = [];
		});
		if(!flag){
			product_info = [];
			return false;
		}
		if(settle_info.length == 0){
			alertTips('warning','请选择产品！');
			return false;
		}
		var settle_amount = +$('#settle_amount').val();
		var discount_amount = +$('#discount_amount').val();
		var total_amount = settle_amount + discount_amount;
		var total_cur_amount =+$('#total_curamount').val();
		if(total_amount != total_cur_amount){
			alertTips('warning', '付款金额+优惠金额 与明细本次付款总额不相等，请修改！');
			return false;
		}
		return settle_info;
	}
	
	
	//确认
	$('#confirm').on('click',function(){
		//检查是否有确认功能
		$.get('check-confirm-settle-payables',function(data,status){
			if(data.Error =='User authentication fails'){
				alertTips('error', '你没有操作权限，如要操作，请向管理员申请');
				return;
			}
			layer.confirm('点击确认入库单将无法编辑，是否确认?', function(index) {
				$.get('confirm-settle-payables',{'id':_id},function(data,status){
					if(status =='success'){
						if(data.Ack =='Success'){
							alertTips('success','确认成功');
							setTimeout(function(){
								window.location.reload();
							},1000);
						}
					} else{
						alertTips('error','网络错误');
					}
				})
				layer.close(index);
			});
		})
	})
	
	
	//名称提示
	$('#stockList').on('mouseenter','.product_name',function(){
		var name = $(this).val();
		if(name !=undefined){
			layer.tips(name, $(this), {
				  tips: [4, '#78BA32']
			});
		}
	});
	
});